package com.dhcc.core.framework.beetl;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.log.LogManager;
import com.dhcc.core.framework.log.factory.LogTaskFactory;
import com.dhcc.core.framework.security.ShiroKit;

import org.beetl.core.ConsoleErrorHandler;
import org.beetl.core.Template;
import org.beetl.core.exception.BeetlException;
import org.beetl.core.exception.ErrorInfo;

public class BeetlErrorHandler extends ConsoleErrorHandler {
    @Override
    public void processExcption(BeetlException ex, Writer writer) {
        super.processExcption(ex, writer);
        LogManager.me().executeLog(LogTaskFactory.exceptionLog(ShiroKit.getCurrentUserOnline(), new BizException(getErrorMsg(ex))));
        Template t = ex.gt.getTemplate("/error.html");
        Map<String, String> map = new HashMap<>();
        map.put("status", "500");
        map.put("error", "模板错误");
        map.put("message", "模板文件加载错误...");
        t.binding(map);
        try {
            writer.write(t.render());
        } catch (IOException e) {
        }
    }

    private String getErrorMsg(BeetlException ex) {
        ErrorInfo error = new ErrorInfo(ex);
        int line = error.getErrorTokenLine();
        StringBuilder sb = new StringBuilder(">>").append(this.getDateTime()).append(":").append(error.getType())
                .append(":").append(error.getErrorTokenText()).append(" 位于").append(line).append("行").append(" 资源:")
                .append(getResourceName(ex.resource.getId()));
        return sb.toString();
    }

}